package csc.daonjpa.java.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import csc.daonjpa.java.transaction.TransactionManager;

/**
 * We are using application managed transaction. It should be good
 * to change to container managed transaction.
 * @author tnguyen256
 *
 */
public class TransactionFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		try {
            TransactionManager.begin();
            chain.doFilter(req, res);
            TransactionManager.commit();
        } catch (RuntimeException e) {
        	// This seems not to be called since Spring MVC handled exception
        	// in controller already
        	TransactionManager.rollback();
        	e.printStackTrace();
            throw e;
        } finally {
        	TransactionManager.close();
        }
	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}
